package com.yk.faceapplication.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;
import com.allinpay.xed.R;
import com.android.volley.VolleyError;
import com.yk.faceapplication.adapter.HotProductAdapter;
import com.yk.faceapplication.adapter.SortAdapter;
import com.yk.faceapplication.callback.ProductCallback;
import com.yk.faceapplication.callback.RequestCallback;
import com.yk.faceapplication.entity.BillProduct;
import com.yk.faceapplication.entity.Member;
import com.yk.faceapplication.entity.ShowProductPoint;
import com.yk.faceapplication.entity.SortModel;
import com.yk.faceapplication.http.RequestUrl;
import com.yk.faceapplication.util.ActivityUtil;
import com.yk.faceapplication.util.CharacterParser;
import com.yk.faceapplication.util.LogDebugger;
import com.yk.faceapplication.util.RequestUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yk_2018/1/14_11:35
 */

public class MarketListActivity extends BaseActivity{
    private final int REQUEST_ADDBILL = 1000;
    private ListView proLV;
    private SortAdapter adapter;
    private EditText searchET;


    private CharacterParser characterParser;
    private List<SortModel> sourceDateList;


    private PinyinComparator pinyinComparator;

    private List<BillProduct> billProducts;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setTitle("小通融e");

        proLV = (ListView) findViewById(R.id.pro_lv);

        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();

        searchET = (EditText) findViewById(R.id.search_et);

        searchET.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 输入的内容变化的监听
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 输入前的监听

            }

            @Override
            public void afterTextChanged(Editable s) {
                // 输入后的监听

                String content = s.toString();
                if(content.equals("")){
                    sourceDateList.clear();
                    sourceDateList.addAll(filledData(billProducts));
                    // 根据a-z进行排序源数据
                    Collections.sort(sourceDateList, pinyinComparator);
                    proLV.setAdapter(adapter);
                }else{
                    sourceDateList.clear();
                    List<BillProduct> tempList = new ArrayList<>();
                    for (BillProduct p : billProducts) {
                        if (p.getBaseProduct().getProductName().contains(content)) {
                            tempList.add(p);
                        }
                    }
                    sourceDateList.addAll(filledData(tempList));
                    // 根据a-z进行排序源数据
                    Collections.sort(sourceDateList, pinyinComparator);
                    adapter.notifyDataSetChanged();
                }
            }
        });

        getBills();
    }

    class PinyinComparator implements Comparator<SortModel> {

        public int compare(SortModel o1, SortModel o2) {
            // 这里主要是用来对ListView里面的数据根据ABCDEFG...来排序
            if (o2.getSortLetters().equals("#")) {
                return -1;
            }
            else if (o1.getSortLetters().equals("#")) {
                return 1;
            }
            else {
                return o1.getSortLetters().compareTo(o2.getSortLetters());
            }
        }
    }
    private final int REQUEST_AUTH = 1003;
    private final int REQUEST_FACE = 1004;
    private void getBills(){
        Map<String, String> form = new HashMap<String, String>();
        form.put("page", "-1");
        form.put("pageSize", "-1");
        if(getIntent().hasExtra("minLoanAmt")){
            form.put("minLoanAmt", getIntent().getStringExtra("minLoanAmt"));
        }
        if(getIntent().hasExtra("loanUse")){
            form.put("loanUse", getIntent().getStringExtra("loanUse"));
        }
        if(getIntent().hasExtra("extend1")){
            form.put("extend1", getIntent().getStringExtra("extend1"));
        }
        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                LogDebugger.info("success:"+jsonObject.toString());
                try {
                    billProducts = JSON.parseArray(jsonObject.getJSONObject("data").getString("records"), BillProduct.class);
                    LogDebugger.info("billProducts:"+billProducts);
                    showProductsPoint(billProducts);
                    sourceDateList = filledData(billProducts);
                    ProductCallback callback = new ProductCallback() {
                        @Override
                        public void clickItem(SortModel model) {
                            if (mApplication.getMember() == null) {
                                Intent intent = new Intent(MarketListActivity.this, LoginActivity.class);
                                startActivityForResult(intent, REQUEST_AUTH);
                                return;
                            }
                            if(!ActivityUtil.isAuth(MarketListActivity.this)){
                                Intent intent = new Intent(MarketListActivity.this, AuthorizeActivity.class);
                                startActivityForResult(intent, REQUEST_AUTH);
                                return;
                            }
                            if(!ActivityUtil.isFace(MarketListActivity.this)){
                                Intent intent = new Intent(MarketListActivity.this, MemberInfoActivity.class);
                                startActivityForResult(intent, REQUEST_FACE);
                                return;
                            }

                            Intent intent = new Intent(MarketListActivity.this,ProductDetailActivity.class);
                            intent.putExtra("loanShowId", model.getUid());
                            startActivityForResult(intent,REQUEST_ADDBILL);
                        }
                    };
                    adapter = new SortAdapter(MarketListActivity.this, sourceDateList,callback);
//                    proLV.setAdapter(adapter);


                    proLV.setAdapter(new HotProductAdapter(MarketListActivity.this,billProducts,callback));
//                    proLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                        @Override
//                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                            LogDebugger.info("click");
//                        }
//                    });
//                    proLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//                        @Override
//                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                            if (mToken == null) {
//                                Intent intent = new Intent(MarketListActivity.this, LoginActivity.class);
//                                startActivityForResult(intent, REQUEST_AUTH);
//                                return;
//                            }
//                            if(!ActivityUtil.isAuth(MarketListActivity.this)){
//                                Intent intent = new Intent(MarketListActivity.this, AuthorizeActivity.class);
//                                startActivityForResult(intent, REQUEST_AUTH);
//                                return;
//                            }
//                            if(!ActivityUtil.isFace(MarketListActivity.this)){
//                                Intent intent = new Intent(MarketListActivity.this, MemberInfoActivity.class);
//                                startActivityForResult(intent, REQUEST_FACE);
//                                return;
//                            }
//                            Intent intent = new Intent(MarketListActivity.this,ProductDetailActivity.class);
//                            intent.putExtra("loanShowId", billProducts.get(position).getLoanShowId());
//                            startActivityForResult(intent,REQUEST_ADDBILL);
//                        }
//                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(VolleyError volleyError) {
                LogDebugger.info("fail:"+volleyError.getMessage());
            }
        };
        RequestUtil.request(this, RequestUrl.GET_BILL_PRODUCTS+"token="+mToken,callback,form);
    }

    private void showProductsPoint(List<BillProduct> billProducts) {
        List<ShowProductPoint> points = new ArrayList<>();
        for(BillProduct billProduct:billProducts){
            ShowProductPoint showProductPoint = new ShowProductPoint();
            showProductPoint.setCategoryId(billProduct.getBaseProduct().getCategoryId());
            showProductPoint.setLoanTerm(billProduct.getMaxLoanTerm());
            showProductPoint.setLoanTermType(billProduct.getLoanTermType());
            showProductPoint.setOrgId(billProduct.getBaseProduct().getOrgId());
            showProductPoint.setProductShowId(billProduct.getLoanShowId());
            showProductPoint.setUserAgentCode("2");
            points.add(showProductPoint);
        }
        String jsonObject = com.alibaba.fastjson.JSONObject.toJSONString(points);
        RequestUtil.request(RequestUrl.DOMAN+"allinpay.stat.all/statall/productlist/add?showType=1&token=" + mToken + "&appType=app",jsonObject);


//        RequestCallback callback = new RequestCallback() {
//            @Override
//            public void success(JSONObject jsonObject) {
//
//            }
//
//            @Override
//            public void fail(VolleyError volleyError) {
//
//            }
//        };
//        RequestUtil.request(this, "http://openapi.allinpaycard.cn/allinpay.stat.all/statall/productlist/add?showType=1&token="+mToken+"&appType=app", callback, jsonObject);
    }

    private void getMember(){
        Map<String, String> form = new HashMap<String, String>();

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                try {
                    Member member = JSON.parseObject(jsonObject.getString("data"),Member.class);
                    mApplication.setMember(member);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void fail(VolleyError volleyError) {

            }
        };
        RequestUtil.request(this, RequestUrl.GET_MEMBER + "token=" + mToken, callback,form);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_ADDBILL){
            if(resultCode == RESULT_OK){
                setResult(RESULT_OK);
                finishAct();
            }
        }else if (requestCode == REQUEST_AUTH || requestCode == REQUEST_FACE ) {
            if (resultCode == RESULT_OK) {
                getMember();
            }
        }
    }

    private List<SortModel> filledData(List<BillProduct> products) {
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for (int i = 0; i < products.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setIcon(products.get(i).getProductIconId());
            sortModel.setName(products.get(i).getBaseProduct().getProductName());
            sortModel.setUid(products.get(i).getLoanShowId());

            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(products.get(i).getBaseProduct().getProductName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            }
            else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }
}
